<?php

namespace app\adminapi\controller;

use support\Request;
use think\facade\Cache;
use app\BaseController as Controller;

/**
 * 公共的方法
 */
class CommonController extends Controller
{
    /**
     * 验证码
     */
    public function captcha(Request $request)
    {
        $param['api'] = true;
        $captcha = \app\common\service\Verify::entry($param);

        return api_response(200, '', [
            'key' => $captcha['key'],
            'src' => $captcha['data'],
            'switch' => true, // 是否启用
        ]);
    }

    /**
     * 设置
     */
    public function setting(Request $request)
    {
        if ($request->post()) {
            return api_response(1, '成功', []);
        }

        return api_response(200, '', [
            'system_name' => '后台管理系统',
            'login_logo_url' => '',
            'login_bg_url' => asset('static/admin/img/login_bg.jpg'),
            'page_title' => 'VueAdmin系统',
            'logo_url' => '',
            'favicon_url' => '',
        ]);
    }

    /**
     * 清除缓存
     */
    public function delCache(Request $request)
    {
        // 清除admin标签的缓存数据
        Cache::tag('admin')->clear();

        return api_response(1, '清除缓存成功！', []);
    }

    /**
     * 文件上传
     */
    public function upload(Request $request)
    {
        /*sleep(3);
        $arrs = [
            asset('uploads/default/honk-kong.jpg'),
            asset('uploads/default/monaco.jpg'),
            asset('uploads/default/new-york.jpg'),
            asset('uploads/default/toronto.jpg'),
        ];
        $url = $arrs[mt_rand(0, 3)];
        $data = [
            'filepath' => $url,
            'full_filepath' => $url,
        ];
        return api_response(1, '成功！', $data);*/

        $respJson = \app\common\service\Uploader::upload($request);
        $result = json_decode($respJson->getContent(), true);
        if ($result['code'] != 1) {
            return api_response(0, $result['msg'], '');
        }
        $data = [
            'name' => $result['filename'],
            'src' => $result['full_filepath'],
            'size' => $result['filesize'],
            'date' => date('Y-m-d H:i:s'),
            //'creator_id' => $this->admin['id'],
            'filepath' => $result['filepath'],
            'full_filepath' => $result['full_filepath'],
            'result' => $result
        ];

        return api_response(1, '成功！', $data);
    }

    /**
     * 文件下载
     */
    public function download(Request $request)
    {
        $file_url = $request->input('file');
        $file_url = urldecode($file_url);
        //$file_size = filesize($file); // 失败
        $file = @file_get_contents($file_url);
        if (!$file) {
            header('location:' . getenv("HTTP_REFERER"));
            exit;
        }
        $file_size = strlen($file);
        $file_name = basename($file_url);

        // 方法一 【有的文件打不开？】
        /*$fp = fopen($file_url, 'r');
        // 下载文件需要用到的头
        header('Content-type: application/octet-stream');
        header('Accept-Ranges: bytes');
        header('Accept-Length:' . $file_size);
        header('Content-Disposition: attachment; filename=' . $file_name);
        $buffer = 1024;
        $file_count = 0;
        // 向浏览器返回数据
        while (!feof($fp) && $file_count < $file_size) {
            $file_con = fread($fp, $buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);*/

        // 方法二
        ob_end_clean();
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); //强制页面不缓存
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . $file_size);
        header('Content-Disposition: attachment; filename=' . $file_name);
        readfile($file_url);
    }

    /**
     * 获取地区
     */
    public function getRegion(Request $request)
    {
        $model = new \app\common\model\Region();
        $list = $model->where([['level', '<', 3]])->select()->toArray();
        $tree = list_to_tree($list, 'area_code', 'parent_code', 'children', 0);

        return api_response(1, '', $tree);
    }
}
